(function(){
  'use strict';

  if (!window.Api) return;

  var ordersTbody = document.getElementById('orders-tbody');
  if (!ordersTbody) return;

  console.log('订单管理器: 初始化');

  // 分页和过滤状态
  var currentPage = 0;
  var pageSize = 50;
  var currentCursor = "";
  var hasMoreData = true;

  // 加载订单数据
  async function loadOrders(resetPagination = false) {
    if (!ordersTbody) return;
    
    console.log('订单管理器: 开始加载订单数据...');
    ordersTbody.innerHTML = '<tr><td colspan="6" class="muted">加载中...</td></tr>';
    
    try {
      // 尝试使用 POST /orders/trades 接口获取订单数据
      console.log('订单管理器: 调用 POST /orders/trades API...');
      
      // 重置分页状态
      if (resetPagination) {
        currentPage = 0;
        currentCursor = "";
        hasMoreData = true;
        console.log('订单管理器: 重置分页状态');
      }

      // 获取搜索和过滤条件
      var filterConditions = getSearchAndFilterConditions();
      
      // 构建请求体参数 (根据API文档，支持分页、搜索、过滤和排序)
      var requestBody = {
        limit: pageSize,  // 每页数量
        start_time: 0,    // 开始时间 (0表示不限制)
        end_time: 0,      // 结束时间 (0表示不限制)
        cursor: currentCursor, // 游标，用于分页
        account_names: [], // 账户名称列表 (空数组表示使用当前用户邮箱)
        connector_names: filterConditions.connector_names, // 连接器名称列表
        trading_pairs: filterConditions.trading_pairs, // 交易对列表 (用于搜索)
        status: filterConditions.status || '', // 状态参数 (单个字符串)
        trade_types: filterConditions.trade_types // 交易类型列表
      };
      
      console.log('订单管理器: 请求体参数:', requestBody);
      var res = await window.Api.request('POST', '/orders/trades', requestBody, true);
      
      // 如果POST请求失败，尝试使用GET /orders/snapshot作为备选
      if (!res.ok && res.status === 422) {
        console.log('订单管理器: POST /orders/trades 返回422错误，尝试使用 GET /orders/snapshot 作为备选...');
        res = await window.Api.request('GET', '/orders/snapshot', null, true);
        console.log('订单管理器: 备选API响应状态:', res.status, res.ok);
      }
      console.log('订单管理器: API响应状态:', res.status, res.ok);
      
      if (!res.ok) {
        var errorText = await res.text();
        console.log('订单管理器: 错误响应内容:', errorText);
        throw new Error('API请求失败: ' + res.status + ' - ' + errorText);
      }
      
      var data = await window.Api.jsonOrThrow(res);
      console.log('订单管理器: API响应数据:', data);
      
      // 根据API响应结构，数据在data字段中
      var orders = data.data || data.orders || [];
      console.log('订单管理器: 当前页订单数量:', orders.length);
      console.log('订单管理器: 订单数据:', orders);
      
      // 更新分页状态
      if (orders.length < pageSize) {
        hasMoreData = false;
        console.log('订单管理器: 已到达最后一页');
      } else {
        hasMoreData = true;
        console.log('订单管理器: 还有更多数据');
      }
      
      // 更新游标 (假设API返回next_cursor字段)
      if (data.next_cursor) {
        currentCursor = data.next_cursor;
        console.log('订单管理器: 更新游标:', currentCursor);
      }
      
      if (!orders.length && currentPage === 0) {
        ordersTbody.innerHTML = '<tr><td colspan="6" class="muted">暂无订单记录</td></tr>';
        return;
      }
      
      // 如果是第一页，清空表格；否则追加数据
      if (currentPage === 0) {
        ordersTbody.innerHTML = '';
      }
      
      // 渲染订单数据
      orders.forEach(function(order, index) {
        console.log('订单管理器: 处理订单', index, ':', order);
        
        var row = document.createElement('tr');
        
        // 时间
        var timeCell = document.createElement('td');
        timeCell.textContent = order.timestamp || order.created_at || order.time || '';
        row.appendChild(timeCell);
        
        // 符号 (交易对)
        var symbolCell = document.createElement('td');
        symbolCell.textContent = order.trading_pair || order.symbol || '';
        row.appendChild(symbolCell);
        
        // 方向 (交易类型)
        var sideCell = document.createElement('td');
        sideCell.textContent = order.trade_type || order.side || '';
        row.appendChild(sideCell);
        
        // 价格
        var priceCell = document.createElement('td');
        priceCell.textContent = order.price || '';
        row.appendChild(priceCell);
        
        // 数量 (金额)
        var quantityCell = document.createElement('td');
        quantityCell.textContent = order.amount || order.qty || order.quantity || '';
        row.appendChild(quantityCell);
        
        // 状态 (显示订单状态或交易ID)
        var statusCell = document.createElement('td');
        // 优先显示API返回的status字段，如果没有则显示order_id
        var statusValue = order.status || order.trade_id || order.order_id || '';
        statusCell.textContent = statusValue;
        row.appendChild(statusCell);
        
        ordersTbody.appendChild(row);
      });
      
      console.log('订单管理器: 订单数据加载完成');
      
      // 添加分页控制按钮
      addPaginationControls();
      
    } catch (err) {
      console.log('订单管理器: 加载失败:', err);
      ordersTbody.innerHTML = '<tr><td colspan="6" class="muted">加载失败: ' + (err && err.message ? err.message : '未知错误') + '</td></tr>';
    }
  }

  // 添加分页控制 (按照策略市场样式)
  function addPaginationControls() {
    // 移除现有的分页控制
    var existingControls = document.getElementById('orders-pagination');
    if (existingControls) {
      existingControls.remove();
    }
    
    // 计算分页信息
    var totalPages = Math.ceil((currentPage + 1) * pageSize / pageSize);
    var currentPageNum = currentPage + 1;
    var totalItems = (currentPage + 1) * pageSize; // 估算总数
    
    // 创建分页控制容器
    var paginationDiv = document.createElement('div');
    paginationDiv.id = 'orders-pagination';
    paginationDiv.style.marginTop = '20px';
    paginationDiv.style.display = 'flex';
    paginationDiv.style.justifyContent = 'space-between';
    paginationDiv.style.alignItems = 'center';
    paginationDiv.style.padding = '16px 0';
    paginationDiv.style.borderTop = '1px solid #eee';
    
    // 左侧页面信息
    var pageInfo = document.createElement('div');
    pageInfo.style.fontSize = '14px';
    pageInfo.style.color = '#666';
    pageInfo.textContent = '第' + currentPageNum + '/' + totalPages + '页·共' + totalItems + '条';
    paginationDiv.appendChild(pageInfo);
    
    // 右侧导航按钮
    var navButtons = document.createElement('div');
    navButtons.style.display = 'flex';
    navButtons.style.gap = '8px';
    
    // 上一页按钮
    var prevBtn = document.createElement('button');
    prevBtn.className = 'btn';
    prevBtn.textContent = '上一页';
    prevBtn.disabled = currentPage === 0;
    prevBtn.onclick = function() {
      if (currentPage > 0) {
        currentPage--;
        console.log('订单管理器: 上一页，当前页:', currentPage + 1);
        loadOrders(false);
      }
    };
    navButtons.appendChild(prevBtn);
    
    // 下一页按钮
    var nextBtn = document.createElement('button');
    nextBtn.className = 'btn';
    nextBtn.textContent = '下一页';
    nextBtn.disabled = !hasMoreData;
    nextBtn.onclick = function() {
      if (hasMoreData) {
        currentPage++;
        console.log('订单管理器: 下一页，当前页:', currentPage + 1);
        loadOrders(false);
      }
    };
    navButtons.appendChild(nextBtn);
    
    paginationDiv.appendChild(navButtons);
    
    // 将分页控制添加到表格后面
    var tableWrap = document.querySelector('.table-wrap');
    if (tableWrap && tableWrap.parentNode) {
      tableWrap.parentNode.appendChild(paginationDiv);
    }
  }

  // 搜索和过滤控制面板 (按照策略市场样式)
  function addSearchAndFilterControls() {
    // 移除现有的控制面板
    var existingControls = document.getElementById('orders-search-filters');
    if (existingControls) {
      existingControls.remove();
    }
    
    // 创建搜索和过滤控制容器
    var controlsDiv = document.createElement('div');
    controlsDiv.id = 'orders-search-filters';
    controlsDiv.style.marginBottom = '20px';
    controlsDiv.style.display = 'flex';
    controlsDiv.style.gap = '12px';
    controlsDiv.style.flexWrap = 'wrap';
    controlsDiv.style.alignItems = 'center';
    controlsDiv.style.justifyContent = 'space-between';
    
    // 左侧搜索和过滤区域
    var leftControls = document.createElement('div');
    leftControls.style.display = 'flex';
    leftControls.style.gap = '12px';
    leftControls.style.alignItems = 'center';
    leftControls.style.flexWrap = 'wrap';
    
    // 搜索输入框
    var searchInput = document.createElement('input');
    searchInput.type = 'text';
    searchInput.placeholder = '搜索交易对 (如: BTC-USDT)';
    searchInput.id = 'orders-search';
    searchInput.style.padding = '8px 12px';
    searchInput.style.border = '1px solid #ddd';
    searchInput.style.borderRadius = '4px';
    searchInput.style.minWidth = '200px';
    leftControls.appendChild(searchInput);
    
    // 交易类型下拉框
    var typeSelect = document.createElement('select');
    typeSelect.id = 'filter-trade-type';
    typeSelect.style.padding = '8px 12px';
    typeSelect.style.border = '1px solid #ddd';
    typeSelect.style.borderRadius = '4px';
    typeSelect.innerHTML = '<option value="">交易类型</option><option value="BUY">买入</option><option value="SELL">卖出</option>';
    leftControls.appendChild(typeSelect);
    
    // 交易所下拉框
    var connectorSelect = document.createElement('select');
    connectorSelect.id = 'filter-connector';
    connectorSelect.style.padding = '8px 12px';
    connectorSelect.style.border = '1px solid #ddd';
    connectorSelect.style.borderRadius = '4px';
    connectorSelect.innerHTML = '<option value="">交易所</option><option value="gate_io">Gate.io</option><option value="binance">Binance</option>';
    leftControls.appendChild(connectorSelect);
    
    // 状态下拉框
    var statusSelect = document.createElement('select');
    statusSelect.id = 'filter-status';
    statusSelect.style.padding = '8px 12px';
    statusSelect.style.border = '1px solid #ddd';
    statusSelect.style.borderRadius = '4px';
    statusSelect.innerHTML = '<option value="">状态</option><option value="FILLED">已完成</option><option value="OPEN">进行中</option><option value="CANCELLED">已取消</option><option value="PENDING">待处理</option>';
    leftControls.appendChild(statusSelect);
    
    // 时间排序下拉框
    var timeSelect = document.createElement('select');
    timeSelect.id = 'filter-time';
    timeSelect.style.padding = '8px 12px';
    timeSelect.style.border = '1px solid #ddd';
    timeSelect.style.borderRadius = '4px';
    timeSelect.innerHTML = '<option value="">时间排序</option><option value="newest">最新</option><option value="oldest">最旧</option>';
    leftControls.appendChild(timeSelect);
    
    controlsDiv.appendChild(leftControls);
    
    // 右侧操作按钮区域
    var rightControls = document.createElement('div');
    rightControls.style.display = 'flex';
    rightControls.style.gap = '8px';
    rightControls.style.alignItems = 'center';
    
    // 搜索按钮
    var searchBtn = document.createElement('button');
    searchBtn.className = 'btn primary';
    searchBtn.textContent = '搜索';
    searchBtn.onclick = function() {
      console.log('订单管理器: 执行搜索');
      loadOrders(true);
    };
    rightControls.appendChild(searchBtn);
    
    // 重置按钮
    var resetBtn = document.createElement('button');
    resetBtn.className = 'btn';
    resetBtn.textContent = '重置';
    resetBtn.onclick = function() {
      searchInput.value = '';
      typeSelect.value = '';
      connectorSelect.value = '';
      statusSelect.value = '';
      timeSelect.value = '';
      console.log('订单管理器: 重置所有条件');
      loadOrders(true);
    };
    rightControls.appendChild(resetBtn);
    
    controlsDiv.appendChild(rightControls);
    
    // 将控制面板添加到页面
    var ordersSection = document.getElementById('orders');
    if (ordersSection) {
      var container = ordersSection.querySelector('.container.section');
      if (container) {
        // 在标题后插入控制面板
        var title = container.querySelector('h2');
        if (title && title.nextSibling) {
          container.insertBefore(controlsDiv, title.nextSibling);
        } else {
          container.insertBefore(controlsDiv, container.firstChild);
        }
      }
    }
  }

  // 获取搜索和过滤条件
  function getSearchAndFilterConditions() {
    var searchInput = document.getElementById('orders-search');
    var tradeType = document.getElementById('filter-trade-type');
    var connector = document.getElementById('filter-connector');
    var status = document.getElementById('filter-status');
    var timeSort = document.getElementById('filter-time');
    
    var conditions = {
      trading_pairs: [], // 搜索关键词通过trading_pairs参数传递
      trade_types: [],
      connector_names: [],
      status: '',
      time_sort: ''
    };
    
    // 搜索关键词 - 通过trading_pairs参数搜索交易对
    if (searchInput && searchInput.value.trim()) {
      conditions.trading_pairs = [searchInput.value.trim()];
    }
    
    // 交易类型过滤
    if (tradeType && tradeType.value) {
      conditions.trade_types = [tradeType.value];
    }
    
    // 交易所过滤
    if (connector && connector.value) {
      conditions.connector_names = [connector.value];
    }
    
    // 状态过滤
    if (status && status.value) {
      conditions.status = status.value;
    }
    
    // 时间排序
    if (timeSort && timeSort.value) {
      conditions.time_sort = timeSort.value;
    }
    
    console.log('订单管理器: 搜索和过滤条件:', conditions);
    return conditions;
  }

  // 暴露函数供外部调用
  window.ordersManager = {
    loadOrders: loadOrders,
    addSearchAndFilterControls: addSearchAndFilterControls
  };

  // 在控制台暴露手动加载函数
  window.manualLoadOrders = loadOrders;

  // 监听页面切换
  window.addEventListener('hashchange', function() {
    var currentHash = window.location.hash;
    console.log('订单管理器: 页面hash变化:', currentHash);
    
    if (currentHash === '#orders') {
      console.log('订单管理器: 检测到订单页面，开始加载数据...');
      loadOrders();
    }
  });

  // 立即检查当前页面状态
  setTimeout(function() {
    var currentHash = window.location.hash;
    console.log('订单管理器: 当前页面hash:', currentHash);
    
    if (currentHash === '#orders') {
      console.log('订单管理器: 检测到订单页面，开始加载数据...');
      addSearchAndFilterControls();
      loadOrders();
    }
  }, 100);

  console.log('订单管理器: 初始化完成');
})();
